import { message } from 'antd';
import { useEffect, useState, useRef, useCallback } from 'react';
import knowService from '@/api/services/knowService';
import { SvgIcon } from '@/components/icon';
import { OptimizedistType, RepetitionType } from '@/types/know/know';
import { formatData } from '@/utils/time';
import { Button } from '@/components/eai-design';
import TipsModals from '@/components/modals/TipsModals';
import useModal from '@/hooks/use-modal/useModal';

interface DocumentRepetitionModalsProps {
  collectionItem: OptimizedistType;
  flag: boolean | undefined;
  deleteDatasetFile?: () => void;
}

function DocumentRepetitionModals({
  collectionItem,
  flag,
  deleteDatasetFile,
}: DocumentRepetitionModalsProps) {
  const [repetitionList, setRepetitionList] = useState<RepetitionType[]>([]);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const containerRef = useRef<HTMLDivElement>(null);
  const currentPage = useRef(1);
  // 标识当前会话，避免上一次未完成请求回写新一轮状态
  const sessionIdRef = useRef(0);
  // 防并发/抖动：在 setLoading 生效前用 ref 先行加锁
  const isFetchingRef = useRef(false);
  const pageSize = 10;
  const modal = useModal('delete');
  const [total, setTotal] = useState(0);
  useEffect(() => {
    sessionIdRef.current += 1;
    currentPage.current = 1;
    setRepetitionList([]);
    setHasMore(true);
    setLoading(false);
    isFetchingRef.current = false;
    setTotal(0);
    // 首次加载第1页，避免受旧闭包影响
    fetchPage(1, true);
  }, [collectionItem]);

  useEffect(() => {
    if (flag !== undefined) {
      changeAllIgnore();
    }
  }, [flag]);

  const fetchPage = useCallback(
    async (page: number, reset: boolean = false) => {
      if (loading || isFetchingRef.current) return;
      const mySession = sessionIdRef.current;
      isFetchingRef.current = true;
      setLoading(true);
      try {
        const res = await knowService.getSimilarityList(
          collectionItem.collectionId,
          collectionItem.appId,
          page,
          pageSize,
          (page - 1) * pageSize,
        );

        if (sessionIdRef.current !== mySession) return; // 过期请求

        const incoming = res.data || [];
        setTotal(res.total || 0);

        setRepetitionList((prev) => (reset ? incoming : [...prev, ...incoming]));
        const newLen = (reset ? 0 : repetitionList.length) + incoming.length;
        currentPage.current = page + 1;
        if (!res.total || newLen >= res.total || incoming.length === 0) {
          setHasMore(false);
        } else {
          setHasMore(true);
        }
      } catch (error) {
        if (sessionIdRef.current === mySession) {
          message.error('获取重复文件列表失败');
        }
      } finally {
        if (sessionIdRef.current === mySession) {
          setLoading(false);
          isFetchingRef.current = false;
        }
      }
    },
    [collectionItem, loading, repetitionList.length],
  );

  const loadMoreData = useCallback(async () => {
    if (loading || isFetchingRef.current) return;
    if (total > 0 && repetitionList.length >= total) {
      setHasMore(false);
      return;
    }
    fetchPage(currentPage.current, false);
  }, [fetchPage, loading, total, repetitionList.length]);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleScroll = () => {
      if (
        container.scrollTop + container.clientHeight >= container.scrollHeight - 20 &&
        !loading &&
        hasMore
      ) {
        loadMoreData();
      }
    };

    container.addEventListener('scroll', handleScroll);
    return () => container.removeEventListener('scroll', handleScroll);
  }, [loadMoreData, loading, hasMore]);

  const changeAllIgnore = async () => {
    try {
      // const datasetIds = repetitionList.map((item) => item.datasetId);
      // const collectionIds = repetitionList.map((item) => item.collectionId);
      await knowService.similarityIngore({
        datasetId: [collectionItem.datasetId],
        collectionId: [collectionItem.collectionId],
      });
      message.success('忽略成功');
    } catch (error) {
      message.error('忽略失败');
    }
  };

  return (
    <div className="rounded-default bg-bg-3 p-4">
      <div className="mb-3 flex items-center justify-between">
        <div className="mb-2 flex min-w-0 flex-1 items-center gap-2 pb-2">
          <SvgIcon size={32} icon="document-ic1" className="mr-2 !h-[32px] !w-[32px]" />
          <div className="min-w-0 flex-1">
            <div className="truncate text-base font-semibold text-text-5">
              {collectionItem.fileName}
            </div>
            <div className="mt-1 text-xs text-text-3">
              {collectionItem.size} · {collectionItem.passTime}
            </div>
          </div>
        </div>
        {deleteDatasetFile && (
          <div className="flex flex-shrink-0 gap-2">
            <Button
              className="rounded-default bg-@brand-color px-4 py-1 text-white"
              onClick={changeAllIgnore}
            >
              忽略该问题
            </Button>
            <Button
              className="rounded-default !bg-error px-4 py-1 !text-white "
              onClick={modal.delete.open}
              type="default"
            >
              删除该文档
            </Button>
          </div>
        )}
      </div>
      <div className="rounded-md bg-text-1 p-4">
        <div className=" text-base font-bold text-orange-400">
          已存在
          {total}
          个相同文件
        </div>
        <div ref={containerRef} className="max-h-[460px] overflow-auto">
          {repetitionList.map((item, index) => (
            <div key={index} className="mb-4  flex py-3 ">
              <div className="pr-3 font-extrabold">
                {index + 1 > 9 ? index + 1 : '0' + (index + 1)}
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex min-w-0 items-center">
                  <div className="flex-none">文件位置：</div>
                  <div
                    className="ml-1 min-w-0 flex-1 truncate text-gray-600"
                    title={`${item.datasetPath}/${item.name}`}
                  >
                    {item.datasetPath}/{item.name}
                  </div>
                </div>
                <div className="mt-2 text-sm text-text-4">
                  <div className="mb-2 mr-4">
                    <span className="">创建时间：</span>
                    {formatData(item.createTime)}
                  </div>
                  <div>
                    <span className="">创建人：</span>
                    {item.username}
                  </div>
                </div>
              </div>
            </div>
          ))}

          {/* {loading && (
          <div className="flex justify-center py-4">
            <div className="border-brand-color h-8 w-8 animate-spin rounded-full border-b-2 border-t-2"></div>
          </div>
        )}

        {!hasMore && <div className="py-4 text-center text-gray-500">没有更多数据了</div>} */}
        </div>
      </div>
      <TipsModals
        okText="删除"
        centered
        open={modal.delete.isOpen}
        onOk={deleteDatasetFile}
        onCancel={modal.delete.close}
      >
        <p>是否删除该文档，剩余检测问题自动跳过，无需处理。</p>
      </TipsModals>
    </div>
  );
}

export default DocumentRepetitionModals;
